(in-package :com.freizl.euler-in-lisp)

;;;
;;; Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun p2 ()
  (apply
   #'+
   (remove-if-not 
    #'evenp
    (fibonacci-list 4000000))))

;;; deprecated, as example for interactive recursive
(defun fib (seq)
  (defun fib-inner (k a b)
    (if (= k 1)
        a
      (fib-inner (1- k) (+ a b) a)))
  (if (< seq 2)
      seq
    (fib-inner seq 1 0)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; quick solutions
;;; The actual result is : 2 8 34 144 ...
;;;                        => E(n) = 4*E(n-1) + E(n-2)
;;;                        :=> F(n) = 4*F(n-3) + F(n-6)
;;;;;;;TODO Implementation
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;                        

(defun list-fibs (limit)
  (let ((fibs '(2 1)))
    (do ((nextfib (+ (car fibs) (cadr fibs))
                  (+ (car fibs) (cadr fibs))))
        ((> nextfib limit))
      (setq fibs (cons nextfib fibs)))
    fibs)) 

(defun problem-2 ()
  (loop for x = 1 then y
        and y = 2 then (+ x y)
        while (< x 4000000)
        when (evenp x)
        sum x))

